﻿/**
Провайдер AnyBalance (http://any-balance-providers.googlecode.com)
*/

var g_headers = {
	'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	'Accept-Charset': 'windows-1251,utf-8;q=0.7,*;q=0.3',
	'Accept-Language': 'ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4',
	'Connection': 'keep-alive',
	'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36',
};

function main() {
	var prefs = AnyBalance.getPreferences();
	var baseurl = 'https://lk.exploitation-gs.ru/';
	AnyBalance.setDefaultCharset('utf-8');
	
	checkEmpty(prefs.login, 'Введите логин!');
	checkEmpty(prefs.password, 'Введите пароль!');
	
	var html = AnyBalance.requestGet(baseurl + '#/login', g_headers);
	
	if(!html || AnyBalance.getLastStatusCode() > 400){
		AnyBalance.trace(html);
		throw new AnyBalance.Error('Ошибка при подключении к сайту провайдера! Попробуйте обновить данные позже.');
	}
	
	html = AnyBalance.requestPost(baseurl + 'api/v2/auth/login/', {
		login: prefs.login,
		password: prefs.password
	}, addHeaders({Referer: baseurl}));
	
    html = AnyBalance.requestGet(baseurl + 'api/v2/auth/current/', g_headers);
    var json = getJson(html);    

	if (!json.data) {
		AnyBalance.trace(html);
		throw new AnyBalance.Error('Не удалось зайти в личный кабинет. Сайт изменен?');
	}
    
	html = AnyBalance.requestGet(baseurl + 'api/v2/auth/accounts/', g_headers);
    
    json = getJson(html);

	var result = {success: true};

    getParam(json.data.tenants[0].short_name, result, 'fio', null, null);
    getParam(json.data.tenants[0].area.house.address, result, 'address', null, null);
    getParam(json.data.tenants[0].number, result, 'acc_num', null, null);
    
    //задаем период - последний год
    var today = new Date();
    var monthNumber = today.getMonth()+1;
    var till_year = today.getFullYear(); 
    var day_number = today.getDay(); 
    var from_year = till_year - 1;
    
    var date_from = from_year + '-' + monthNumber + '-' + day_number;
    var date_till = till_year + '-' + monthNumber + '-' + day_number;
 
    html = AnyBalance.requestGet(baseurl + 'api/v2/reports/trial_balance/lk.json/?accounts=' + json.data.tenants[0]._id + '&area=' + json.data.tenants[0].area._id + '&date_from=' + date_from + '&date_till=' + date_till, g_headers);
    json = getJson(html);
	
	getParam(json.data.caption.saldo_out, result, 'balance', null, null);
	
	AnyBalance.setResult(result);
}